﻿package net.wangit.framework.util;

import java.util.List;

import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.Table;
import net.wangit.jdbc.table.Column;
import net.wangit.jdbc.table.TableMeta;
import net.wangit.jdbc.table.TableMetaFactory;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class TablePrinter {

	private static final Log log = LogFactory.getLog(TablePrinter.class);

	private TablePrinter() {
	}

	public static void print(Table table) {
		if (!log.isDebugEnabled())
			return;
		StringBuffer out;
		int maxLength;
		List<Column> columns;
		List<ColumnRow> rows;
		out = new StringBuffer("\n[");
		out.append(table.getTableName()).append("]\n");
		maxLength = 0;
		TableMeta meta = TableMetaFactory.getTableMeta(table.getDomain(),
				table.getTableName());
		columns = meta.getColumns();
		for (int i = 0; i < columns.size(); i++) {
			Column column = columns.get(i);
			int length = column.getName().length();
			maxLength = length <= maxLength ? maxLength : length;
		}

		maxLength++;
		rows = table.getRows();
		if (rows.size() == 0) {
			out.append("(none)");
			log.debug(out);
			return;
		}
		try {
			for (int i = 0; i < rows.size(); i++) {
				ColumnRow row = rows.get(i);
				out.append(
						StringUtil.fill(
								new StringBuilder(i).append(getOperation(row))
										.toString(), 20, '-', true)).append(
						"\n");
				for (int j = 0; j < columns.size(); j++) {
					String name = columns.get(j).getName();
					out.append(StringUtil.fill(name, maxLength, ' ', true))
							.append(row.get(name));
					String key = row.getPrimaryKey(name);
					if (!Checker.isEmpty(key))
						out.append("(").append(key).append(")");
					out.append("\n");
				}

			}

			log.debug(out);
		} catch (Exception e) {
			log.warn("print table error:", e);
		}
		return;
	}

	private static final String getOperation(ColumnRow row) {
		if (row.isUpdateRow())
			return "(update)";
		if (row.isInsertRow())
			return "(insert)";
		else
			return "(delete)";
	}

}
